package com.lanou.tipsy.adapter.main;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.util.Log;

import com.lanou.tipsy.fragment.mv.MvFragment;
import com.lanou.tipsy.fragment.person.MineFragment;
import com.lanou.tipsy.fragment.rank.RankFragment;
import com.lanou.tipsy.fragment.recommend.RecommendFragment;
import com.lanou.tipsy.fragment.singer.classify.SingerFragment;
import com.lanou.tipsy.fragment.songsList.SongsListsFragment;

import java.lang.ref.SoftReference;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

/**
 * Created by dllo on 15/10/20.
 * 主页的viewPager适配器
 */
public class MainViewPagerFragmentAdapter extends FragmentStatePagerAdapter {
    //定义一个数据集合对象,存储类型是fragment
    public static final String TAG = "MainViewPagerFragmentAdapter";
    private Map<String, SoftReference<ArrayList<Fragment>>> fragments = new HashMap<>();
    private ArrayList<Fragment> datas;

    public MainViewPagerFragmentAdapter(FragmentManager fm) {
        super(fm);
        addFragment(TAG);
        datas = getFragmentsByPath(TAG);
    }

    //保存软引用到HashMap
    public void addFragment(String path) {

        SoftReference<ArrayList<Fragment>> softReference = fragments.get(path);
        //判断是否存在软引用
        if (softReference == null) {
            Log.i("test", TAG + "->添加软引用对象");
            //强引用的对象
            ArrayList<Fragment> datas = new ArrayList<>();
            datas.add(new MineFragment());
            datas.add(new RecommendFragment());
            datas.add(new SingerFragment());
            datas.add(new RankFragment());
            datas.add(new SongsListsFragment());
            datas.add(new MvFragment());
            //软引用fragment集合对象
            softReference = new SoftReference<>(datas);
            datas = null;
            //添加该对象到map中使其缓存
            fragments.put(path, softReference);
        }
    }

    //获取软引用对象
    public ArrayList<Fragment> getFragmentsByPath(String path) {
        Log.i("test", TAG + "->获取软引用对象");
        //从缓存中获取软引用的集合对象
        SoftReference<ArrayList<Fragment>> softReference = fragments.get(path);
        //判断是否存在软引用
        if (softReference == null) {
            return null;
        }
        //去除集合对象,如果由于内存不足集合对象被回收,将取得空
//        datas = softReference.get();
//        return datas;
        return softReference.get();
    }

    @Override
    public Fragment getItem(int position) {
        return datas != null && datas.size() > 0 ? datas.get(position) : null;
    }

    @Override
    public int getCount() {
        return datas != null && datas.size() > 0 ? datas.size() : 0;
    }
}
